<?php
/**
 * Fang_Controller_Admin
 * 
 * 作者:  姚刚 (yaogang@the9sense.com)
 * 创建时间: 2011-03-19 06:57:06
 * 修改记录: 
 * 
 * $Id: Admin.php 18 2011-04-17 12:50:07Z coosuu $
 */

class Fang_Controller_Admin extends Controller_Action {

    const LOGIN_KEY = '^du*_&';

    /**
     * indexAction
     * 后台首页 
     * 
     * @return void
     */
    public function indexAction() {

        if (!$this->_isLogin()) {
            return $this->response->setRedirect('/admin/login');
        }

        return $this->response->setRedirect('/admin/intro');
    }

    /**
     * introAction
     * 简介 
     * 
     * @return void
     */
    public function introAction() {

        //  check login
        if (!$this->_isLogin()) {
            return $this->response->setRedirect('/admin/login');
        }

        $introService =& Service::factory('Intro');

        // post and save
        if ($this->request->isPost()) {

            $posts = $this->request->postx('telphone', 'address', 'shopName', 'indexPic', 'contactId', 'aboutIds', 'newsCid');
            $test = array_filter($posts);
            if (!$test) {
                return $this->_errorMessage('请认真填写表单');
            }

            foreach ($posts as $k => $v) {
                $$k = $v;
            }

            try {
                $res = $introService->save($telphone, $address, $shopName, $indexPic, $contactId, $aboutIds, $newsCid);
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if (!$res) {
                return $this->_errorMessage('更新失败，请重试');
            }

            return $this->response->setRedirect('/admin/intro');
        }

        // show
        try {
            $intro = $introService->get();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('intro', $intro);

        return $this->view->render('admin/intro');
    }

    /**
     * loginAction
     * 登录 
     * 
     * @return void
     */
    public function loginAction() {

        if ($this->_isLogin()) {
            return $this->response->setRedirect('/admin');
        }

        if ($this->request->isPost()) {
            $name = trim($this->request->post('name'));
            $passwd = trim($this->request->post('passwd'));
            if (!$name || !$passwd) {
                return $this->_errorMessage('请填写用户名和密码');
            }

            $managerService =& Service::factory('Manager');
            $manager = $managerService->getByHandle($name);
            if (!$manager || $passwd != $manager['m_password']) {
                return $this->response->setRedirect('/admin/login');
            }

            $this->response->setCookie('adminId', $manager['mid']);
            $this->response->setCookie('adminName', $manager['m_handle']);
            $this->response->setCookie('sig', md5($manager['mid'] . $manager['m_handle'] . self::LOGIN_KEY));
            return $this->response->setRedirect('/admin');
        }

        return $this->view->render('admin/login');
    }

    /**
     * logoutAction
     * 退出登录 
     * 
     * @return void
     */
    public function logoutAction() {

        $this->response->setCookie('adminId', '', time() - 86400);
        $this->response->setCookie('adminName', '', time() - 86400);
        $this->response->setCookie('sig', '', time() - 86400);
        return $this->response->setRedirect('/admin');
    }

    /**
     * _isLogin
     * 验证是否登录 
     * 
     * @return void
     */
    private function _isLogin() {

        $adminId = $this->request->cookie('adminId');
        $adminName = $this->request->cookie('adminName');
        $sig = $this->request->cookie('sig');

        if (md5($adminId.$adminName.self::LOGIN_KEY) == $sig) {
            return true;
        }

        return false;
    }

    /**
     * _getLoginId 
     * 
     * @return void
     */
    private function _getLoginId() {

        return $this->request->cookie('adminId');
    }

    /**
     * _getLoginName 
     * 
     * @return void
     */
    private function _getLoginName() {

        return $this->request->cookie('adminName');
    }

    private function _message($message, $type = 'succ') {

        $this->view->set('message', $message);
        if ($type == 'succ') {
            return $this->view->render('admin/message/success');
        }

        return $this->view->render('admin/message/error');
    }

    private function _succMessage($message) {

        return $this->_message($message, 'succ');
    }

    private function _errorMessage($message) {

        return $this->_message($message, 'error');
    }

    /**
     * managerAddAction
     * 添加管理员 
     * 
     * @return void
     */
    public function managerAddAction() {

        //  check login
        if (!$this->_isLogin()) {
            return $this->response->setRedirect('/admin/login');
        }

        if ($this->request->isPost()) {
            $posts = $this->request->postx('handle', 'name', 'password', 'email', 'qq', 'mobile');
            $test = array_filter($posts);
            if (!$test) {
                return $this->_errorMessage('请填写表单');
            }

            foreach ($posts as $k => $v) {
                $kk = $v;
            }

            try {
                $managerService =& Service::factory('Manager');

                // check manager isExists
                if ($managerService->isExists($handle)) {
                    return $this->_errorMessage('用户已经存在');
                }

                $res = $managerService->add($handle, $name, $password, $email, $mobile, $qq);
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if (!$res) {
                return $this->_errorMessage('添加管理员失败，请重试');
            }

            return $this->response->setRedirect('/admin/managerList');
        }

        return $this->view->render('admin/manager/add');
    }

    /**
     * managerEditAction 
     * 管理员编辑
     * 
     * @return void
     */
    public function managerEditAction() {

        //  check login
        if (!$this->_isLogin()) {
            return $this->response->setRedirect('/admin/login');
        }

        $managerService =& Service::factory('Manager');

        if ($this->request->isPost()) {
            $posts = $this->request->postx('mid', 'name', 'password', 'email', 'mobile', 'qq');
            $test = array_filter($posts);
            if (!$test) {
                return $this->_errorMessage('请填写表单');
            }

            foreach ($posts as $k => $v) {
                $kk = $v;
            }

            try {
                $res = $managerService->update($mid, null, $name, $password, $email, $mobile, $qq);
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if (!$res) {
                return $this->_errorMessage('编辑管理员失败，请重试');
            }

            return $this->response->setRedirect('/admin/managerList');
        }

        $mid = intval($this->request->get('mid'));
        if (!$mid) {
            return $this->_errorMessage('mid不能为空');
        }

        // get manager info
        $manager = $managerService->get($mid);

        $this->view->set('manager', $manager);

        return $this->view->render('admin/manager/edit');
    }

    /**
     * managerListAction
     * 管理员列表 
     * 
     * @return void
     */
    public function managerListAction() {

        $page = intval($this->request->get('page', 1));
        if (!$page) {
            $page = 1;
        }

        $pageOptions = array('currentPage' => 1,
                             'perPage' => 15);

        try {
            $managerService =& Service::factory('Manager');
            $lists = $managerService->listAll($pageOptions);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('lists', $lists);
        $this->view->set('page', $pageOptions);
        return $this->view->render('admin/manager/list');
    }

    /**
     * articleListAction
     * 文章列表 
     * 
     * @return void
     */
    public function articleListAction() {

        $page = intval($this->request->get('page', 1));
        $perPage = 15;
        $pageOptions = array('currentPage' => $page,
                             'perPage' => $perPage);

        try {
            $articleService =& Service::factory('Article');
            $lists = $articleService->listAll($pageOptions);

            $cateService =& Service::factory('Cate');
            $cateLists = $cateService->listAll();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $cates = array();
        if (is_array($cateLists) && $cateLists) {
            foreach ($cateLists as $c) {
                $cates[$c['cid']] = $cates['c_title'];
            }
        }

        if (is_array($lists) && $lists) {
            foreach ($lists as $k => $l) {
                $lists[$k]['c_title'] = $cates[$l['cid']];
            }
        }

        $this->view->set('lists', $lists);
        $this->view->set('page', $pageOptions);
        return $this->view->render('admin/article/list');
    }

    /**
     * articleEditAction
     * 编辑文章 
     * 
     * @return void
     */
    public function articleEditAction() {

        $aid = intval($this->request->get('aid'));
        if (!$aid) {
            return $this->_errorMessage('参数错误');
        }

        if ($this->request->isPost()) {
            $posts = $this->request->postx();
            $idList = explode(',', $posts['itemIdsList']);
            if (!$idList) {
                return $this->_errorMessage('参数错误');
            }

            $title = $posts['title_0'];
            $published = $posts['time_0'];
            $cateid = $posts['cate_0'];

            $content = $pids = array();
            foreach ($idList as $id) {
                $type = $posts['type_'.$id];
                if (!$type || !in_array($type, array('title', 'text', 'pic'))) {
                    continue;
                }

                if ($type == 'text') {
                    $content[] = array('title' => $posts['title_'.$id],
                                       'text' => $posts['text_'.$id],
                                       'type' => 'text');
                }

                if ($type == 'pic') {
                    $pids[] = $posts['picid_'.$id];
                    $content[] = array('picid' => $posts['picid_'.$id],
                                       'desc' => $posts['desc_'.$id],
                                       'src' => $posts['src_'.$id],
                                       'thumb_src' => $posts['thumb_src_'.$id],
                                       'type' => 'pic');
                }
            }

            $data = array('a_title' => $title,
                          'a_publisher_mid' => $this->_getLoginId(),
                          'cid' => $cateid,
                          'a_content' => json_encode($content),
                          'a_published' => $published);
            try {
                $articleService =& Service::factory('Article');
                $res = $articleService->update($aid, $data);

                if ($pids) {
                    $photoService =& Service::factory('Photo');
                    $photoService->updateByPids($pids, array('aid' => $aid));
                }
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if ($pids) {
                $url = '/admin/articleSetCover?aid='.$aid;
            } else {
                $url = '/admin/articleList';
            }

            return $this->response->setRedirect($url);
        }

        try {
            $articleService =& Service::factory('Article');
            $article = $articleService->getInfo($aid);

            $cateService =& Service::factory('Cate');
            $cates = $cateService->listAll();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('article', $article);
        $this->view->set('cates', $cates);
        return $this->view->render('admin/article/edit');
    }

    /**
     * articleAddAction 
     * 新增文章
     * 
     * @return void
     */
    public function articleAddAction() {

        if ($this->request->isPost()) {
            $posts = $this->request->postx();
            $idList = explode(',', $posts['itemIdsList']);
            if (!$idList) {
                return $this->_errorMessage('参数错误');
            }


            $title = $posts['title_0'];
            $published = $posts['time_0'];
            $cateid = $posts['cate_0'];

            $content = $pids = array();
            foreach ($idList as $id) {
                $type = $posts['type_'.$id];
                if (!$type || !in_array($type, array('title', 'text', 'pic'))) {
                    continue;
                }

                if ($type == 'text') {
                    $content[] = array('title' => $posts['title_'.$id],
                                       'text' => $posts['text_'.$id],
                                       'type' => 'text');
                }

                if ($type == 'pic') {
                    $pids[] = $posts['picid_'.$id];
                    $content[] = array('picid' => $posts['picid_'.$id],
                                       'desc' => $posts['desc_'.$id],
                                       'src' => $posts['src_'.$id],
                                       'thumb_src' => $posts['thumb_src_'.$id],
                                       'type' => 'pic');
                }
            }

            $data = array('a_title' => $title,
                          'a_publisher_mid' => $this->_getLoginId(),
                          'cid' => $cateid,
                          'a_content' => json_encode($content),
                          'a_published' => $published);
            try {
                $articleService =& Service::factory('Article');
                $aid = $articleService->add($data);

                if ($pids) {
                    $photoService =& Service::factory('Photo');
                    $photoService->updateByPids($pids, array('aid' => $aid));
                }
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if ($pids) {
                $url = '/admin/articleSetCover?aid='.$aid;
            } else {
                $url = '/admin/articleList';
            }

            return $this->response->setRedirect($url);
        }

        try {
            $cateService =& Service::factory('Cate');
            $cates = $cateService->listAll();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('cates', $cates);
        return $this->view->render('admin/article/add');
    }

    /**
     * articleSetCoverAction 
     * 
     * @return void
     */
    public function articleSetCoverAction() {
 
        $aid = intval($this->request->get('aid'));
        if (!$aid) {
            return $this->_errorMessage('参数错误');
        }

        if ($this->request->isPost()) {

            $pid = intval($this->request->post('pid'));
            if (!$pid) {
                return $this->_errorMessage('请选择一张图片');
            }

            $src = trim($this->request->post('src_'.$pid));
            if (!$src) {
                return $this->_errorMessage('参数错误');
            }

            $data = array('a_cover_id' => $pid,
                          'a_cover_src' => $src);
            try {
                $articleService =& Service::factory('Article');
                $articleService->update($aid, $data);
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            return $this->response->setRedirect('/admin/articleSetCover?aid=' . $aid);
        }


        try {
            $articleService =& Service::factory('Article');
            $info = $articleService->getInfo($aid);

            $photoService =& Service::factory('Photo');
            $photos = $photoService->listByAid($aid);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('coverid', $info['a_cover_id']);
        $this->view->set('aid', $aid);
        $this->view->set('photos', $photos);
        return $this->view->render('admin/article/setCover');
    }
    /**
     * articleRemoveAction
     * 删除文章 
     * 
     * @return void
     */
    public function articleRemoveAction() {

        $aid = intval($this->request->get('aid'));
        if (!$aid) {
            return $this->_errorMessage('参数错误');
        }

        try {
            $service =& Service::factory('Article');
            $res = $service->remove($aid);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        if (!$res) {
            return $this->_errorMessage('删除失败');
        }

        return $this->_succMessage('删除成功');
    }

    /**
     * cateAddAction 
     * 新增分类
     * 
     * @return void
     */
    public function cateAddAction() {

        if ($this->request->isPost()) {
            $posts = $this->request->postx('title', 'level', 'link', 'parentId');

            try {
                $service =& Service::factory('Cate');
                $res = $service->add($posts['title'], $posts['level'], $posts['link'], $posts['parentId']);
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if (!$res) {
                return $this->_errorMessage('添加失败');
            }

            return $this->_succMessage('添加成功');
        }

        try {
            $service =& Service::factory('Cate');
            $lists = $service->listAll();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('lists', $lists);
        return $this->view->render('admin/cate/add');
    }

    /**
     * cateEditAction 
     *　编辑分类
     * 
     * @return void
     */
    public function cateEditAction() {

        $cid = intval($this->request->get('cid'));
        if (!$cid) {
            return $this->_errorMessage('参数错误');
        }

        $service =& Service::factory('Cate');

        if ($this->request->isPost()) {
            $posts = $this->request->postx('cid', 'title', 'level', 'link', 'parentId');

            try {
                $res = $service->update($cid, $posts['title'], $posts['level'], $posts['link'], $posts['parentId']);
            } catch (Exception $e) {
                return $this->_errorMessage($e->getMessage());
            }

            if (!$res) {
                return $this->_errorMessage('编辑失败');
            }

            return $this->_succMessage('编辑成功');
        }

        try {
            $cate = $service->getInfo($cid);
            $lists = $service->listAll();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('cate', $cate);
        $this->view->set('lists', $lists);
        return $this->view->render('admin/cate/edit');
    }

    /**
     * cateRemoveAction 
     * 删除分类
     * 
     * @return void
     */
    public function cateRemoveAction() {

        $cid = intval($this->request->get('cid'));
        if (!$cid) {
            return $this->_errorMessage('参数错误');
        }

        try {

            $cateService =& Service::factory('Cate');
            $res = $cateService->remove($cid);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        if (!$res) {
            return $this->_errorMessage('删除失败，请重试');
        }

        return $this->_succMessage('删除成功');

    }

    /**
     * cateListAction
     * 分类列表 
     * 
     * @return void
     */
    public function cateListAction() {

        try {
            $cateService =& Service::factory('Cate');
            $lists = $cateService->listAll();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('lists', $lists);
        return $this->view->render('admin/cate/list');
    }

    /**
     * messageListUnpassAction 
     * 
     * @return void
     */
    public function messageListUnpassAction() {

        $page = intval($this->request->get('page', 1));
        $pageOptions = array('currentPage' => $page,
                             'perPage' => 15);

        try {
            $messageService =& Service::factory('Message');
            $lists = $messageService->listUnpass($pageOptions);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('messages', $lists);
        $this->view->set('page', $pageOptions);
        return $this->view->render('admin/message/list');
    }

    /**
     * messageListPassAction 
     * 
     * @return void
     */
    public function messageListPassAction() {

        $page = intval($this->request->get('page', 1));
        $pageOptions = array('currentPage' => $page,
                             'perPage' => 15);

        try {
            $messageService =& Service::factory('Message');
            $lists = $messageService->listPass($pageOptions);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('messages', $lists);
        $this->view->set('page', $pageOptions);
        return $this->view->render('admin/message/list');
    }

    /**
     * messageRemoveAction 
     * 
     * @return void
     */
    public function messageRemoveAction() {

        $meid = intval($this->request->get('meid'));
        if (!$meid) {
            return $this->_errorMessage('参数错误');
        }

        try {
            $messageService =& Service::factory('Message');
            $res = $messageService->remove($meid);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        if (!$res) {
            return $this->_errorMessage('删除失败，请稍后重试');
        }

        return $this->_succMessage('删除成功');
    }

    /**
     * messageReplyAction 
     * 
     * @return void
     */
    public function messageReplyAction() {

        if (!$this->request->isPost()) {
            return $this->_errorMessage('非法请求，请重试');
        }

        $posts = $this->request->postx('replyContent', 'meid', 'replyid');
        $content = strip_tags($posts['replyContent']);
        $meid = intval($posts['meid']);
        if (!$content || !$meid) {
            return $this->_errorMessage('参数错误');
        }

        $messageService =& Service::factory('Message');

        $replyId = intval($posts['replyid']);
        try {
            if ($replyId) {
                $res = $messageService->update($replyId, array('me_content' => $content));
            } else {
                $res = $messageService->add('Mr.F', $content, $meid);
            }
            $messageService->pass($meid);
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        if (!$res) {
            return $this->_errorMessage('回复失败，请重试');
        }

        return $this->_succMessage('回复成功');
    }

    /**
     * uploadAction 
     * 
     * @return void
     */
    public function uploadAction() {

        if (!$this->request->isPost()) {
            return $this->_uploadMessage(1, 1011, '非法请求');
        }

        try {

            // 验证登录
            if (!$this->_isLogin()) {
                return $this->_uploadMessage(1, 1001, '请先登录');
            }

            $file = $this->request->file('Filedata');
            $fileName = trim($this->request->post('Filename'));

            $photoService =& Service::factory('Photo');
            $addRes = $photoService->upload($file, $fileName);
            if (!$addRes) {
                return $this->_uploadMessage(1, 1009, '上传失败!');
            }

            return $this->_uploadMessage(0, $addRes);
        } catch (Exception $e) {
            return $this->_uploadMessage(1, 1010, $e->getMessage());
        }
    }

    /**
     * _uploadMessage 
     * 
     * @param  mixed $resultCode 
     * @param  mixed $errorCode 
     * @param  string $message 
     * @return void
     */
    private function _uploadMessage($resultCode, $errorCode, $message = '') {

        if ($resultCode == 1) {
            $errorCode = 0;
        }

        $ret = json_encode(array('resultCode' => $resultCode, 'id' => $errorCode, 'describe' => $message));
        return $this->response->setBody($ret);
    }

    /**
     * _ajaxMessage 
     * 
     * @param  mixed $code 
     * @param  string $message 
     * @return void
     */
    private function _ajaxMessage($code, $message = '') {

        $ret = json_encode(array('code' => $code, 'content' => $message));
        return $this->response->setBody($ret);
    }

    /**
     * articleAddModule 
     * 
     * @return void
     */
    public function articleAddModuleAction() {

        $num = intval($this->request->get('maxItemId'));
        $picid = intval($this->request->get('picid'));
        $type = $this->request->get('type');
        if (!$num || !in_array($type, array('text', 'pic'))) {
            return $this->_ajaxMessage(1, '参数错误');
        }

        if ($type == 'pic') {
            if (!$picid) {
                return $this->_ajaxMessage(1, '参数错误');
            }

            $photoService =& Service::factory('Photo');
            $pic = $photoService->getInfo($picid);
            if (!$pic) {
                return $this->_ajaxMessage(1, '图片不存在');
            }

            $this->view->set('pic', $pic);
        }
        $this->view->set('num', $num+1);
        $content = $this->view->render('admin/article/' . $type . 'Module', true);
        return $this->_ajaxMessage(0, $content);
    }

    /**
     * photoListAction 
     * 
     * @return void
     */
    public function photoListAction() {

        $introService =& Service::factory('intro');
        if ($this->request->isPost()) {

            $pid = intval($this->request->post('pid'));
            if (!$pid) {
                return $this->_errorMessage('参数错误');
            }

            try {
                $introService->save(null, null, null, $pid);
            } catch (Exception $e) {
                return $this->_errorMessage($e);
            }

            return $this->_succMessage('首页图片设置成功');
        }

        try {
            $photoService =& Service::factory('Photo');
            $pageOptions = array('currentPage' => 1,
                                 'perPage' => 16);
            $photos = $photoService->listAll($pageOptions);

            $intro = $introService->get();
        } catch (Exception $e) {
            return $this->_errorMessage($e->getMessage());
        }

        $this->view->set('photos', $photos);
        $this->view->set('intro', $intro);
        return $this->view->render('admin/photo');
    }
}
